package com.itqian.seller.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itqian.seller.entity.FoodCategory;
import com.itqian.seller.entity.FoodInfo;
import com.itqian.seller.mapper.FoodCategoryMapper;
import com.itqian.seller.mapper.FoodInfoMapper;
import com.itqian.seller.service.FoodInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itqian.seller.vo.FoodInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜品信息表 服务实现类
 * </p>
 *
 * @author shishuqian
 * @since 2022-03-21
 */
@Service
public class FoodInfoServiceImpl extends ServiceImpl<FoodInfoMapper, FoodInfo> implements FoodInfoService {

    @Autowired
    private FoodInfoMapper foodInfoMapper;

    @Autowired
    private FoodCategoryMapper foodCategoryMapper;

    @Override
    public Map<String, Object> list(Integer storeId,Integer page, Integer size) {
        Page<FoodInfo> foodInfoPage = new Page<>(page,size);
        QueryWrapper<FoodInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("store_id",storeId)
                .orderByDesc("create_time");
        Page<FoodInfo> foodPage = foodInfoMapper.selectPage(foodInfoPage, wrapper);
        return this.transform(foodPage);
    }

    @Override
    public Map<String, Object> findAllByCategory(Integer categoryId,Integer page,Integer size) {
        Page<FoodInfo> foodInfoPage = new Page<>(page,size);
        QueryWrapper<FoodInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("category_type",categoryId)
                .orderByDesc("create_time");
        Page<FoodInfo> foodPage = foodInfoMapper.selectPage(foodInfoPage, wrapper);
        return this.transform(foodPage);
    }


    private   Map<String, Object> transform(Page<FoodInfo> foodInfoPage){
        List<FoodInfo> records = foodInfoPage.getRecords();
        List<FoodInfoVO> list = new ArrayList<>();
        for (FoodInfo record : records) {
            FoodInfoVO foodInfoVO = new FoodInfoVO();
            BeanUtils.copyProperties(record,foodInfoVO);
            FoodCategory one = this.foodCategoryMapper.selectById(record.getCategoryType());
            //有时分类删除了，菜品没删除，就会查询出null，这样避免空指针异常
            if (one == null){
                foodInfoVO.setCategoryName("未分类(null)");
            }else{
                foodInfoVO.setCategoryName(one.getCategoryName());
            }

            list.add(foodInfoVO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("content",list);
        map.put("size",foodInfoPage.getSize());
        map.put("total",foodInfoPage.getTotal());
        return map;
    }
}
